/**
 * Created by shandianhaizan on 16/6/15.
 */


'use strict';
var router = require('express').Router();
var models = require('../model/index');
var Query = require('../lib/query');
var AV = require('leanengine');
var docLib  = require('../lib/doc');
var Doc =  docLib.doc;
var BatchSave = docLib.batchSave;
var _  = require('lodash');
var xls = require('./excel');

var findModel = function (req) {
    var params = req.params;
    var model = models[params.model];
    if (!model) {
        throw new Error("not found model");
    }
    return model;
};




var getAll = function (req, res, next) {
    try{
        var query = new Query(req.params.model, req.query);
        query.getAll().then(function (arg_result) {
            res.send({code: 0, data: arg_result});
        }).catch(next);
    }catch(err){
        next(err)
    }

};


var addNew = function (req, res, next) {
    try{
        var doc  = new Doc(req.params.model, req.body);
        doc.save().then(function (result) {
            res.send({code: 0, data: result});
        }).catch(next)
    }catch(err){
        next(err)
    }

};


var getOne = function (req, res, next) {
    var query = new Query(req.params.model);
    query.getOneById(req.params.id).then(function (arg_result) {
        res.send({code: 0, data: arg_result});
    }).catch(next);
};





var deleted = function (req, res, next) {
    try{
        var doc  = new Doc(req.params.model, {id:req.params.id, deleted: true});
        doc.save().then(function (result) {
            res.send({code: 0, data: result});
        }).catch(next)
    }catch(err){
        next(err)
    }
};




var batchSave = function (req, res, next) {
    var model = models["Production"];
    var modelObject = model.getObject;
    var ids = req.body.ids;
    var type = req.body.type;
    var avObjectArray = [];
    var setType = {
        onSale: function (newModel) {
            newModel.set("state", '0');
        },
        offSale: function (newModel) {
            newModel.set("state", '1');
        },
        discount: function (newModel) {
            newModel.set("discount", '0');
        },
        deleted: function (newModel) {
            newModel.set("deleted", true);
        }
    };
    for (var i = 0, l = ids.length; i < l; i++) {
        var newModel = new modelObject();
        newModel.set("objectId", ids[i]);
        setType[type](newModel);
        avObjectArray.push(newModel);
    }
    AV.Object.saveAll(avObjectArray).then(function (todo) {
        res.send({code: 0});
    }).catch(next);
};



var importData = function (req, res, next) {
    var filePath = req.body.url;
    xls.readExcel(filePath, function (err, data) {
        if(err) return res.send({code:1 , err:err});
        var model = models["Production"];
        var modelObject = model.getObject;
        if (!data || !data[0] || !data[0].data) return;
        var datas = data[0].data;
        var avObjectArray = [];
        for (var i = 1, l = datas.length; i < l; i++) {
            var d = datas[i];
            var newModel = new modelObject();
            if(d[1]) d[1] = d[1]+'';
            ["objectId", "code", "name", "seq", "cost", "stock", "freight"].forEach(function (v, i) {
                if (d[i]) newModel.set(v, d[i]);
            });
            avObjectArray.push(newModel);
        }
        AV.Object.saveAll(avObjectArray).then(function (todo) {
            res.send({code: 0});
        }).catch(next);
    });
};


var removeParent = function (req, res, next) {
    var model = findModel(req);
    var id = req.params.id;
    var query = model.getQuery();
    var modelObject = model.getObject;
    query.equalTo("pid", id);
    var avObjectArray = [];
    //官方文档 批量操作 例子 没用???
    query.find().then(function (todos) {
        for (var i = 0; i < todos.length; i++) {
            var todo = todos[i];
            var newModel = new modelObject();
            newModel.set('objectId' , todo.id);
            newModel.set('pid', "0");
            avObjectArray.push(newModel);
        }
        return AV.Object.saveAll(avObjectArray).then(function (success) {
            res.send({code: 0});
        },function(err){
            console.log(err);
        }).catch(next);
    });

};


var addUser= function (req, res, next) {
    try{
        var avObjectArray = [];
        var params = req.body;
        var customerDoc  = new Doc("Customer", params);
        avObjectArray.push(customerDoc.newObject);
        var checkFiledRepeat = function(field,errorMsg ) {
           var query = new Query("Customer");
           return query.checkRepeat(params, field, errorMsg);
        };
        var checkUsernameRepeat = checkFiledRepeat.bind(null,"username", "用户名" );
        var checkMobilePhoneNumberRepeat = checkFiledRepeat.bind(null,"mobilePhoneNumber", "手机号" );
        var checkEmailRepeat = checkFiledRepeat.bind(null,"email", "邮箱" );
        var findUser = function(){
            var query = new Query("_User",{'username':params.username});
            return query.find().then(function (users) {
                var userParam = _.pick(params, ['username','password', 'mobilePhoneNumber', 'email']);
                if (users.length !== 0) {
                    userParam.objectId = users[0].id;
                }
                var userDoc  = new Doc("_User", userParam);
                return userDoc.newObject;
            });
        };

        var save = function(user){
            avObjectArray.push(user);
            return BatchSave(avObjectArray).then(function (data) {
                res.send({code: 0, data: data[0]});
            })
        };

        checkUsernameRepeat().then(
            checkMobilePhoneNumberRepeat).then(
            checkEmailRepeat).then(findUser).then(save).catch(next);
    }catch(err){
        next(err)
    }

};


var exportOrder = function(req, res, next){
     var name = req.body.name;
     var data = req.body.data;
     xls.exportExcel(data,name,function(err, filePath){
         if(err) return next(err);
         res.send({code: 0, url:filePath});
     })
};



router.get('/:model', getAll);

router.get('/:model/:id', getOne);

router.post('/:model', addNew);

router.post('/delete/:model/:id', deleted);


router.post('/removeParent/:model/:id', removeParent);


router.post('/production/batchSave', batchSave);

router.post('/production/import', importData);


router.post('/production/import', importData);


router.post('/user/save', addUser);


router.post('/order/export', exportOrder);



module.exports = router;


